package com.web.security.provider;

import org.apache.log4j.Logger;
import org.springframework.security.AuthenticationException;
import org.springframework.security.BadCredentialsException;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.providers.dao.DaoAuthenticationProvider;
import org.springframework.security.providers.encoding.PasswordEncoder;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;

import com.web.security.util.SecurityUtils;

public class CustomUserDetailsService extends DaoAuthenticationProvider{
	private PasswordEncoder passwordEncoder;
	private UserDetailsService userDetailsService;
	
	private static final Logger LOGGER = Logger.getLogger(CustomUserDetailsService.class);
	
	@Override
	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
		LOGGER.info("==========================Step CustomUserDetailsService");
		LOGGER.info("==========================getName "+authentication.getName() );
		LOGGER.info("==========================getCredentials "+authentication.getCredentials());
		LOGGER.info("==========================getAuthorities "+authentication.getAuthorities() );
		LOGGER.info("==========================getDetails "+authentication.getDetails() );
		
		
		LOGGER.info("==========================getUsername "+userDetails.getUsername() );
		LOGGER.info("==========================getPassword "+userDetails.getPassword() );
		LOGGER.info("==========================getAuthorities "+userDetails.getAuthorities() );

		
		
        if (SecurityUtils.isNull(authentication.getCredentials()) || SecurityUtils.isNull(authentication.getName())) {
            throw new BadCredentialsException("Wrong username or password");
        }
        
        if(!passwordEncoder.isPasswordValid(userDetails.getPassword(),(String) authentication.getCredentials(),  null)){
        	throw new BadCredentialsException("Wrong username or password");
        }
       
	}
	
	@Override
	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	@Override
	public void setUserDetailsService(UserDetailsService userDetailsService) {
		this.userDetailsService = userDetailsService;
		super.setUserDetailsService(this.userDetailsService);
	}
}
